package com.le.tester.imooc.oldfairy.coding.sorting;

import org.junit.Test;

/**
 * createTime：2023/5/23 9:55
 * description：选择排序
 */
public class SelectionSort implements IMutableSorter {
    @Override
    public void sort(int[] arr) {
        //左闭右开
        int length = arr.length - 1;
        for (int i = length; i >= 0; i--) {
            //两两比较，进步比较，从后面进行了排序
            int j = maxIndex(arr, 0, i + 1);
            //最大的值会放在最后
            Helper.swap(arr, i, j);
        }

    }

    private int maxIndex(int[] arr, int i, int j) {
        int max = Integer.MIN_VALUE;

        int maxIndex = j - 1;

        for (int k = j - 1; k >= i; k--) {
            if (max < arr[k]) {
                max = arr[k];
                maxIndex = k;
            }
        }
        return maxIndex;
    }

    @Test
    public void testSelectionSort(){
        this.sort(new int[]{1, 2, 3, 5, 4, 8, 9, 256, 7, 8, 9});
    }
}
